package org.dh2580.dev.tools.util;

import java.util.List;
import java.util.function.Function;

/**
 * @Author: hao.deng
 * @Date: 2019/12/30-下午4:54
 */
public final class StringUtil {

    public static final String WHITE_SPACE = "";

    public static final String BLANK_SPACE = " ";

    private StringUtil() {
    }

    public static String join(List<? extends Object> sources, String separator) {
        return join(sources, separator, Object::toString);
    }

    public static <T> String join(List<T> sources, String separator, Function<T, String> toStringFunc) {
        if (sources == null) {
            return null;
        }

        if (separator == null) {
            separator = WHITE_SPACE;
        }

        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < sources.size(); i++) {
            if (i > 0) {
                builder.append(separator);
            }
            builder.append(toStringFunc.apply(sources.get(i)));
        }

        return builder.toString();
    }

    public static boolean isNullOrEmpty(String string) {
        return string == null || string.isEmpty();
    }

    public static boolean isNullOrBlank(String string) {
        if (isNullOrEmpty(string)) {
            return true;
        }

        for (int i = 0; i < string.length(); i++) {
            if (!Character.isWhitespace(string.charAt(i))) {
                return false;
            }
        }

        return true;
    }

    public static String nullToEmpty(String string) {
        return string == null ? WHITE_SPACE : string;
    }

    public static String emptyToNull(String string) {
        return isNullOrEmpty(string) ? null : string;
    }
}
